const stringifyUrl = obj => {
  const url = Object.keys(obj)
    .reduce((target, curr) => {
      if (curr !== 'url') {
        target += `${curr}=${obj[curr]}&`
      }
      return target
    }, obj.url + '?')
    .slice(0, -1)
  return url
}

export default async function handler(req, res) {
  const url = stringifyUrl(req.query)
  if (!url.includes('.flv')) {
    res.status(200).json({ msg: 'no flv stream' })
    return
  }
  const request = url.includes('https') ? require('https') : require('http')

  // 创建请求
  const streamReq = request.get(url)
  // 监听错误事件
  streamReq.on('error', function (error) {
    res.status(500).json({ msg: 'load stream error', error })
  })

  try {
    streamReq.on('response', stream => {
    // 处理302问题。
    if (stream.statusCode == 302) {
      res.writeHead(302, {
        'Location': '/api/loadflv?url=' + stream.headers.location.replace('?','&')
      })
      res.end()
    } else {
      res.setHeader('Content-Type', 'video/x-flv')
      stream.pipe(res)
    }
    })
  } catch (error) {
    res.status(500).json({ msg: 'load stream error', error })
  }
}
